#!/bin/bash

path=`pwd`
#编译命令
mvn="/var/jenkins_home/tools/hudson.tasks.Maven_MavenInstallation/maven3.3.9/bin/mvn"
server1="192.168.5.4"
server2="192.168.3.111"
server3="192.168.3.110"
build_dir="mediator-ws/mediator-ws/target"
war_name=`ls ${WORKSPACE}/${build_dir} |grep war`
project_name="mediator-ws"
config_name="appconfigure"
config_dir="appconfigure/environments/dev/FileList"
ip=${!server}
tomcat_path="/opt/tomcat8/webapps"

if [ "$branch" == "" ];then
    echo "分支不可为空" && exit 1
fi

:>mediator-git.log
:>appconfigure.log

#是否需要编译
if [ "X$isBuild" == "Xtrue" ];then
    echo "===============代码编译==============="  
    #echo ${WORKSPACE}
    if [ -d ${WORKSPACE}/mediator-ws ];then
        rm -rf ${WORKSPACE}/mediator-ws
    fi
    
    if [ -d ${WORKSPACE}/appconfigure ];then
        rm -rf ${WORKSPACE}/appconfigure
    fi
    
    #拉取分支
    git clone -b ${branch} git@gitee.com:mytj/${project_name}.git >> mediator-git.log 2>&1
    
    if grep -E 'not found' mediator-git.log;then
        echo "$branch 分支不存在" && exit 1
    fi
    
    #拉取配置文件
    git clone -b master git@gitee.com:mytj/${config_name}.git >> appconfigure.log 2>&1
    
    if grep -E 'not found' appconfigure.log;then
        echo "配置文件 master 分支不存在" && exit 1
    fi
    
    cd ${WORKSPACE}/mediator-ws
    $mvn clean install -Pver
    if [ $? -eq 0 ];then
        echo "===============代码编译成功==============="
    fi
fi


echo "===============代码发布==============="
#关闭tomcat
tomcat_pid=`ssh -t -p 22 root@$ip ps -ef | grep /opt/tomcat8/ | grep -v grep | awk -F ' ' '{print $2}'`
if [ "X${tomcat_pid}" != "X" ];then
    ssh -t -p 22 root@$ip "kill -9 ${tomcat_pid}"
fi

cd ${WORKSPACE}/${build_dir}
mv ${war_name} ${project_name}.war 
scp ${project_name}.war root@$ip:${tomcat_path}/
#判断远程服务器上文件夹是否存在
if ssh root@$ip test -e ${tomcat_path}/${project_name}/;then 
   ssh -t -p 22 root@$ip "rm -rf ${tomcat_path}/${project_name} && echo exist"   
fi  
#手动解压
ssh -t -p 22 root@$ip "cd ${tomcat_path} && mkdir ${project_name} && unzip ${project_name}.war -d ${project_name}/ && rm -f ${project_name}.war && echo success"
cd ${WORKSPACE}/${config_dir}
mv mediator-config.properties config.properties && mv mediator-mongodb.properties mongodb.properties
scp config.properties mongodb.properties root@$ip:${tomcat_path}/${project_name}/WEB-INF/classes/
if [ $? -eq 0 ];then
    echo "===============代码发布成功==============="
fi

#开启tomcat
ssh -t -p 22 root@$ip "source /etc/profile && /opt/tomcat8/bin/startup.sh"